<template>
  <a-card :bordered="false">
    <div class="card-title">{{ $route.meta.title }}</div>
    <div class="table-operator">
      <div style="margin-bottom:10px">
        <template v-if="status">
          <a-button v-action:export type="primary" @click="handleExport">导出数据</a-button>
          <a-button v-action:export type="primary" @click="handleExportAvatar" style="margin-left:10px">导出头像
          </a-button>
          <a-button
            v-action:export
            :disabled="selectedRowKeys.length===0"
            type="primary"
            @click="handleExport(1)"
            style="margin-left:10px">导出所选数据
          </a-button>
          <a-button
            v-action:export
            :disabled="selectedRowKeys.length===0"
            type="primary"
            @click="handleExportAvatar(1)"
            style="margin-left:10px">导出所选头像
          </a-button>
        </template>
        <template v-else>
          <a-button
            v-action:audit
            :disabled="selectedRowKeys.length===0"
            type="primary"
            @click="handleBatchApproved"
          >批量审核通过
          </a-button>
        </template>
      </div>
      <a-row :gutter="10">
        <a-form :layout="formLayout" labelAlign="left" :form="searchForm" @submit="handleSubmit">
          <a-col :span="6">
            <a-form-item label="学员姓名" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-input
                placeholder="请输入学员姓名"
                v-decorator="['full_name']"
              />
            </a-form-item>
            <!--            <a-form-item label="考试时间" :labelCol="labelCol" :wrapperCol="wrapperCol">-->
            <!--              <a-range-picker-->
            <!--                format="YYYY-MM-DD"-->
            <!--                v-decorator="['create_time']"-->
            <!--              />-->
            <!--            </a-form-item>-->
          </a-col>
          <a-col :span="6">
            <a-form-item label="身份证号" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-input
                placeholder="请输入身份证号"
                v-decorator="['idnumber']"
              />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="所属用户" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-tree-select
                v-decorator="['channel_id']"
                :treeData="userList"
                :replaceFields="{children:'children', title:'real_name', key:'store_user_id', value: 'store_user_id' }"
                style="width: 100%"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                placeholder="请选择用户"
                allow-clear
                tree-default-expand-all
              >
              </a-tree-select>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <!--            <a-form-item label="考试分数" :label-col="labelCol" :wrapper-col="wrapperCol">-->
            <!--              <a-input-->
            <!--                placeholder="请输入考试分数"-->
            <!--                v-decorator="['idnumber']"-->
            <!--              />-->
            <!--            </a-form-item>-->
            <a-form-item :label-col="labelCol" :wrapper-col="{ style: 'width: 100%;float:left' }">
              <a-button type="primary" html-type="submit" icon="search">点击搜索</a-button>
              <a-button style="margin-left:10px" @click="handleReset">重置表单</a-button>
            </a-form-item>
          </a-col>
        </a-form>
      </a-row>
    </div>
    <s-table
      ref="table"
      rowKey="application_id"
      :loading="isLoading"
      :columns="columns"
      :data="loadData"
      :pageSize="15"
      tableLayout="auto"
      :scroll="{x:true}"
      :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
    >
      <div slot="status" slot-scope="text, item">
        <a-tag v-if="text===0">待审核</a-tag>
        <a-tag v-if="text===1" color="green">审核通过</a-tag>
      </div>
      <div slot="sign_url" slot-scope="text, item">
        <a :href="text" target="_blank"><img :src="text" style="height:60px"></a>
      </div>

      <div slot="comsign" slot-scope="text, item">
        <a :href="text" target="_blank"><img :src="text" style="height:60px"></a>
        <a-popover
          trigger="click">
          <template slot="content">
            <div
              style="text-align: center;background: #fff;padding: 20px 10px 20px 10px"
              :id="'signCode'+item.application_id">
              <img v-if="codeUrl" :src="codeUrl" style="width: 150px;height: 150px;margin-top: 10px;">
              <div v-if="codeUrl" style="text-align: center;white-space: nowrap;">
                <div
                  style="padding:5px;background:#e8e8e8;color: #a40000;border-radius: 6px;margin-top: 5px"
                >
                  <span style="font-weight: bold">{{ item.user.full_name }}</span> {{ item.subject.subject_name
                  }}[{{ item.subject_level.level_name }}]
                </div>
                <div
                  style="padding:5px;background:#e8e8e8;color: #a40000;border-radius: 6px;margin-top: 5px"
                >{{ item.user.idnumber }}
                </div>
              </div>
              <div v-else style="text-align: center">
                <a-spin style="margin: 0 auto" />
              </div>
            </div>
            <div style="text-align:center">
              <a
                @click="downloadWxCode(item.user.full_name+' - 签名二维码','signCode'+item.application_id)">下载二维码</a>
            </div>
          </template>
          <a @click="handleShowH5Code(item)">修改签名</a>
        </a-popover>
      </div>

      <div slot="accumulate_learn" slot-scope="text, item">
        <a style="font-weight: 600;font-size: 20px;">{{ text }}</a>
      </div>
      <div slot="exam_score" slot-scope="text, item">
        <a style="font-weight: 600;font-size: 20px;margin-right: 10px">{{ text }}</a>
      </div>
      <div slot="channel" slot-scope="text, item">
        <template v-if="item.is_edit==false">
          <a v-if="currentUser.new_super==1" @click="item.is_edit=true">{{ text }}</a>
          <span v-else>{{ text }}</span>
        </template>
        <template v-else>
          <a-tree-select
            v-if="item.is_edit"
            v-model="item.channel.store_user_id"
            :treeData="userList"
            :replaceFields="{children:'children', title:'real_name', key:'store_user_id', value: 'store_user_id' }"
            style="width: 100px"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            placeholder="请选择所属用户"
            tree-default-expand-all
            @change="updateChannel($event,item)"
          />
          <a @click="item.is_edit=false"> 取消</a>
        </template>
      </div>
      <div slot="last_avatar" slot-scope="text, item">
        <a :href="text" target="_blank"><img :src="text" style="height:60px"></a>
      </div>
      <div class="actions" slot="action" slot-scope="text, item">
        <template v-if="item.status===0">
          <a
            style="color: #04be02"
            v-action:audit
            @click="handleApproved(item)">审核通过</a>
        </template>
        <a v-action:show_exam v-if="!isEmpty(item.last_paper)" @click="handleShowPaper(item)">查看试卷</a>
        <a v-action:delete @click="handleDelete(item)">删除</a>
      </div>
    </s-table>
  </a-card>
</template>
<script>
import * as Api from '@/api/user/application'
import { STable, UploadImage } from '@/components'
import { isEmpty } from '@/utils/util'
import * as userApi from '@/api/store/user'
import QRCode from 'qrcodejs2'

import html2canvas from 'html2canvas'

const columns = [
  {
    title: '所属用户',
    dataIndex: 'channel.real_name',
    scopedSlots: { customRender: 'channel' }
  },
  {
    title: '审核状态',
    dataIndex: 'status',
    scopedSlots: { customRender: 'status' }
  },
  {
    title: '人脸头像',
    dataIndex: 'face_file.external_url',
    scopedSlots: { customRender: 'sign_url' }
  },
  {
    title: '承诺签名',
    dataIndex: 'comsign_file.external_url',
    scopedSlots: { customRender: 'comsign' }
  },
  // {
  //   title: '交卷签名',
  //   dataIndex: 'examsign_file.external_url',
  //   scopedSlots: { customRender: 'sign_url' }
  // },
  {
    title: '学员姓名',
    dataIndex: 'user.full_name',
    align: 'center'
  },
  {
    title: '身份证号',
    align: 'center',
    dataIndex: 'user.idnumber'
  },
  {
    title: '报考工种',
    align: 'center',
    dataIndex: 'subject.subject_name'
  },
  {
    title: '工种等级',
    align: 'center',
    dataIndex: 'subject_level.level_name'
  },
  {
    title: '累计学时（分钟）',
    align: 'center',
    dataIndex: 'accumulate_learn',
    scopedSlots: { customRender: 'exam_score' }
  },
  {
    title: '考试分数',
    align: 'center',
    dataIndex: 'exam_score',
    scopedSlots: { customRender: 'exam_score' }
  },
  {
    fixed: 'right',
    title: '操作',
    dataIndex: 'action',
    width: '100px',
    scopedSlots: { customRender: 'action' }
  }
]
export default {
  name: 'Index',
  props: {
    status: {
      type: Number,
      default: 0
    }
  },
  components: {
    STable,
    UploadImage
  },
  data () {
    return {
      currentUser: this.$store.getters.userInfo,
      searchForm: this.$form.createForm(this),
      formLayout: 'horizontal',
      labelCol: {
        style: 'width: 70px;float:left;margin-right:10px;white-space: nowrap;\n' +
          'text-overflow: ellipsis;\n' +
          '-o-text-overflow: ellipsis;\n' +
          'overflow: hidden;'
      },
      wrapperCol: { style: 'width: calc( 95% - 70px );float:left' },
      codeUrl: '',
      // 查询参数
      queryParam: {
        status: this.status
      },
      // 正在加载
      isLoading: false,
      // 表头
      columns,
      // 加载数据方法 必须为 Promise 对象
      loadData: param => {
        return Api.list({ ...param, ...this.queryParam })
          .then(response => {
            response.data.list.data.forEach(item => {
              item.is_edit = false
            })
            return response.data.list
          })
      },
      userList: [],
      selectedRowKeys: [],
      selectedRow: []
    }
  },
  created () {
    this.getUserTreeList()
  },
  methods: {
    handleShowH5Code (item) {
      var element = document.createElement('div')
      var url = window.location.origin + '/h5/#/pages/editSignImg/index?application_id=' + item.application_id
      const qrcode = new QRCode(element, {
        text: url,
        width: 200,
        height: 200,
        colorDark: '#333333',
        colorLight: '#ffffff',
        correctLevel: QRCode.CorrectLevel.L
      })
      const canvas = qrcode._el.getElementsByTagName('canvas')[0]
      this.codeUrl = canvas.toDataURL()
    },
    downloadWxCode (filename, dom) {
      html2canvas(
        document.getElementById(dom),
        {
          // backgroundColor: null, // 画出来的图片有白色的边框,不要可设置背景为透明色（null）
          useCORS: true, // 支持图片跨域
          scale: 1// 设置放大的倍数
        }
      ).then(canvas => {
        const a = document.createElement('a')
        a.href = canvas.toDataURL('image/png')
        a.download = filename
        a.click()
      })
    },

    async updateChannel (channel_id, item) {
      await Api.edit({ apiId: item.application_id, form: { channel_id } })
      this.$message.success('操作成功', 1.5)
      this.handleRefresh()
    },
    getUserTreeList () {
      userApi.getUserTreeList().then(({ data: { list } }) => {
        this.userList = list
      })
    },
    onSelectChange (selectedRowKeys, selectedRow) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRow = selectedRow
    },
    isEmpty,
    handleExamLog (item) {
      this.$refs.ExamLogModel.open()
    },

    handleSubmit (e) {
      e.preventDefault()
      const { searchForm: { validateFields } } = this
      validateFields((errors, values) => {
        if (errors) {
          return false
        }
        this.queryParam = { ...this.queryParam, ...values }
        this.handleRefresh(true)
      })
    },
    handleReset () {
      this.searchForm.resetFields()
    },

    handleExport (ck = 0) {
      const params = this.queryParam
      if (ck === 1) {
        params.application_id = this.selectedRowKeys
      }
      // if (params.create_time) {
      //   params.create_time = params.create_time[0].format('YYYY-MM-DD') + '/' + params.create_time[1].format('YYYY-MM-DD')
      // }
      Api.exportExcel({ ...params, ...{ export: 1 } })
    },
    handleExportAvatar (ck = 0) {
      const params = this.queryParam
      if (ck === 1) {
        params.application_id = this.selectedRowKeys
      }

      if (params.create_time) {
        params.create_time = params.create_time[0].format('YYYY-MM-DD') + '/' + params.create_time[1].format('YYYY-MM-DD')
      }
      Api.exportAvatar({ ...params }).then(({ data: { url } }) => {
        window.open(url)
      })
    },

    handleBatchApproved () {
      const applicationIds = this.selectedRowKeys
      const app = this
      const modal = this.$confirm({
        title: '您确定要将选中的记录标记为审核通过吗?',
        // content: '删除后不可恢复',
        onOk () {
          return Api.batchEdit({ apiId: applicationIds, form: { status: 1 } })
            .then((result) => {
              app.$message.success(result.message, 1.5)
              app.handleRefresh()
            })
            .finally(result => {
              modal.destroy()
            })
        }
      })
    },
    /**
     * 新增记录
     */
    handleAdd () {
      // this.$refs.AddForm.add()
    },

    /**
     * 编辑记录
     */
    handleShowPaper (item) {
      window.open(window.location.origin + '/index.php?s=/api/index/paperpreview&paper_id=' + item.last_paper.paper_id)
    },

    /**
     * 审核通过
     */
    handleApproved ({ application_id }) {
      const app = this
      const modal = this.$confirm({
        title: '您确定要审核通过该记录吗?',
        // content: '删除后不可恢复',
        onOk () {
          return Api.edit({ apiId: application_id, form: { status: 1 } })
            .then((result) => {
              app.$message.success(result.message, 1.5)
              app.handleRefresh()
            })
            .finally(result => {
              modal.destroy()
            })
        }
      })
    },

    /**
     * 删除记录
     */
    handleDelete (item) {
      const app = this
      const modal = this.$confirm({
        title: '您确定要删除该记录吗?',
        content: '删除后不可恢复',
        onOk () {
          return Api.deleted({ apiId: item['application_id'] })
            .then((result) => {
              app.$message.success(result.message, 1.5)
              app.handleRefresh()
            })
            .finally(result => {
              modal.destroy()
            })
        }
      })
    },

    /**
     * 刷新列表
     * @param Boolean bool 强制刷新到第一页
     */
    handleRefresh (bool = false) {
      this.$refs.table.refresh(bool)
    },

    /**
     * 检索查询
     */
    onSearch () {
      this.handleRefresh(true)
    }
  }
}
</script>
